package main

import (
	"io/ioutil"
	"os"

	"github.com/pelletier/go-toml"
)

// configFilename 配置文件名
const configFilename = "config.toml"

// config 程序配置，加载配置文件后会覆盖
var config = &configuration{
	DevIP:         "192.168.10.251",
	SNMPPort:      161,
	SNMPVer:       "v2c",
	SNMPCommunity: "public",
	SNMPv3Params: &snmpV3Params{
		Username:          "user1",
		SecurityLevel:     "authPriv",
		AuthAlgorithm:     "md5",
		AuthPassphrase:    "123456789",
		PrivacyAlgorithm:  "des",
		PrivacyPassphrase: "123456789",
	},
	IntervalMs:     1000,
	MaxTokenNumber: 1,
	OIDs: []string{
		".1.3.6.1.2.1.1.1.0",
		".1.3.6.1.2.1.1.2.0",
		".1.3.6.1.2.1.1.3.0",
		".1.3.6.1.2.1.1.4.0",
		".1.3.6.1.2.1.1.5.0",
		".1.3.6.1.2.1.1.6.0",
		".1.3.6.1.2.1.1.7.0",
	},
}

type snmpV3Params struct {
	SecurityLevel     string `toml:"security_level" comment:"可选：AuthPriv, AuthNoPriv, NoAuthNoPriv"`
	Username          string `toml:"username"`
	AuthAlgorithm     string `toml:"auth_algorithm" comment:"可选：MD5, SHA, SHA224, SHA256, SHA384, SHA512"`
	AuthPassphrase    string `toml:"auth_passphrase"`
	PrivacyAlgorithm  string `toml:"privacy_algorithm" comment:"可选：DES, AES, AES192, AES256, AES192C, AES256C"`
	PrivacyPassphrase string `toml:"privacy_passphrase"`
}

type configuration struct {
	// DevIP 设备的IP地址
	DevIP string `toml:"dev_ip"`

	// DevSNMPPort 设备的 SNMP 端口
	SNMPPort uint16 `toml:"snmp_port"`

	// DevSNMPVer SNMP 版本
	SNMPVer string `toml:"snmp_ver" comment:"可选：v1, v2c, v3"`

	// DevSNMPCommunity SNMP 共同体
	SNMPCommunity string `toml:"snmp_community"`

	// SNMPv3Params SNMPv3 参数
	SNMPv3Params *snmpV3Params `toml:"snmp_v3_params"`

	// IntervalMs 轮询间隔
	IntervalMs int `toml:"interval_ms" comment:"轮询间隙时间，毫秒"`

	// MaxTokenNumber 一次交互获取多少个OIDs
	MaxTokenNumber int `toml:"max_token_number" comment:"一次 GET 请求携带多少个 OIDs"`

	// OIDs 获取的OIDs
	OIDs []string `toml:"oids"`
}

// loadConfig 加载配置文件
func loadConfig() error {
	buf, err := ioutil.ReadFile(configFilename)
	if err != nil {
		if os.IsNotExist(err) {
			mustSaveConfig()
			return nil
		}
		return err
	}
	return toml.Unmarshal(buf, config)
}

// mustSaveConfig 保存配置到文件
func mustSaveConfig() {
	buf, _ := toml.Marshal(config)
	err := ioutil.WriteFile(configFilename, buf, 0644)
	if err != nil {
		panic(err)
	}
}
